<template>
    <div class="upload-pic clear-float">
        <input type="file" class="upload-input" name="image" accept="image/*" capture="camera" @change="uploadPic($event)">
        <img id="show-pic" :src="imgSrc" alt="">
    </div>
</template>

<script>
import EXIF from "../../static/exif"
import qs from "qs"
export default {
    mounted () {
    },
    methods: {
        uploadPic (e) {
            // 获取当前选中的文件
            var file = e.target.files[0];
            // console.log("file:", file);

            this.imgObj.imgType = file.type;

            console.log("fileName: " + file.name);
            console.log("fileSize: " + file.size);
            console.log("fileType: " + file.type);

            // 检查文件类型
            if(["jpeg", "png", "gif", "jpg"].indexOf(file.type.split("/")[1]) < 0){
                // 报错方式
                alert("文件类型错误！");
                return;
            }

            // 图片压缩之旅
            this.transformFileToDataUrl(file);
        },
        // 将file转成dataUrl - Base64格式
        transformFileToDataUrl (file) {
            var _this = this;
            var imgCompassMaxSize = 1024 * 500 * 4/3; // 超过 100k 就压缩

            // 读取文件
            var reader = new FileReader();

            reader.readAsDataURL(file);
            // file转dataUrl是个异步函数，要将代码写在回调里
            reader.onload = function(e) {
                var dataUrl = e.target.result;
                console.log("type:", typeof dataUrl);

                // 展示图片-压缩前
                // document.querySelector("#show-pic").src = dataUrl;


                console.log("Base64:", dataUrl.length);

                // 图片不压缩
                if(dataUrl.length < imgCompassMaxSize) {
                    _this.uploadImg(dataUrl);

                // 图片压缩
                } else {
                    _this.compress(dataUrl);
                }
            };
        },
        // 使用canvas绘制图片并压缩
        compress (dataUrl) {
            var _this = this;
            this.imgObj.ratio = (this.imgObj.size * 1024) / (dataUrl.length);
            console.log("ratio:", this.imgObj.ratio);

            var img = new Image();
            // console.log("img:", img);
            img.src = dataUrl;
            console.log("beforeCompress:", dataUrl.length);

            img.onload = function () {
                // 方向
                var orient;
                EXIF.getData(img, function () {
                    orient = EXIF.getTag(this, "Orientation");
                });
                console.log("orient:", orient);

                // 画布
                var canvas = document.createElement("canvas");
                // document.body.append(canvas);
                // 设置画布的宽高
                canvas.width = img.width;
                canvas.height = img.height;

                console.log("w:", img.width);
                console.log("h:", img.height);

                // 画笔
                var ctx = canvas.getContext("2d");

                // 执行Canvas的drawImage语句
                // ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

                // 画图
                //判断图片拍摄方向的 - 旋转角度
                if (orient == 1 || orient == undefined) {
                    // 执行Canvas的drawImage语句
                    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

                } else {
                    // 保存状态
                    ctx.save();
                    // 设置画布上的(0, 0)位置，也就是旋转的中心点
                    ctx.translate(canvas.width / 2, canvas.height / 2);


                    if (orient == 3) {

                        // 把画布旋转180度
                        ctx.rotate(180 * Math.PI / 180);
                        // 执行Canvas的drawImage语句
                        ctx.drawImage(img,- canvas.width / 2, - canvas.height / 2,  canvas.width, canvas.height);

                    } else if (orient == 6) {

                        // 重新设置画布的宽高
                        canvas.width = img.height;
                        canvas.height = img.width;
                        // 重设画布的(0, 0)位置
                        ctx.translate(canvas.width / 2, canvas.height / 2);

                        // 把画布旋转90度
                        ctx.rotate(90 * Math.PI / 180);
                        // 执行Canvas的drawImage语句
                        // ctx.drawImage(img, Number(y) - canvas.height / 2, Number(x) - canvas.width / 2, canvas.width, canvas.height);
                        ctx.drawImage(img, - canvas.height / 2, - canvas.width / 2, canvas.height, canvas.width);

                    } else if (orient == 8) {

                        // 重新设置画布的宽高
                        canvas.width = img.height;
                        canvas.height = img.width;
                        // 重设画布的(0, 0)位置
                        ctx.translate(canvas.width / 2, canvas.height / 2);
                        // 把画布旋转270度
                        ctx.rotate(270 * Math.PI / 180);
                        // 执行Canvas的drawImage语句
                        ctx.drawImage(img, - canvas.height / 2, - canvas.width / 2, canvas.height, canvas.width);
                    }


                    // 恢复状态
                    ctx.restore();
                }

                // 压缩图片
                // var compressedDataUrl = canvas.toDataURL("image/jpeg", imgObj.ratio);
                console.log(_this.imgObj);
                var compressedDataUrl = canvas.toDataURL(_this.imgObj.imgType, _this.imgObj.ratio);

                console.log("afterCompress", compressedDataUrl.length);

                _this.uploadImg(compressedDataUrl);
                console.log(compressedDataUrl.length);
            }
        },
        uploadImg (data) {
            var _this = this;
            // var data = data;
            console.log(data.length);
            // debugger
            var blob = this.convertBase64UrlToBlob(data);
            var formData = new FormData();
            formData.append("source", "h5");
            formData.append("sim", "13212345656");
            formData.append("file", blob, "file_"+Date.parse(new Date())+".jpg");

            // console.log("imgData:", formData.get("sim"));

            let config = {
                headers:{"Content-Type": "multipart/form-data"}
            }; //添加请求头
            this.axios.post("http://img.shouqiev.com/upload.json", formData, config)
            .then( res => {
                console.log(res);
                // 上传成功
                if (res.data.code == 200) {
                    // this.imgSrc = res.data.modelData.url;
                    this.sendMsgToParent("receiveImg", res.data.modelData.url);
                    // this.sendMsgToParent("receiveImg", res.data);
                }
            })
        },
        /**
         * 将以base64的图片url数据转换为Blob
         * @param urlData
         * 用url方式表示的base64图片数据
         */
        convertBase64UrlToBlob(urlData){
            var arr = urlData.split(','), mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
            while(n--){
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], {type:mime});
        },

        sendMsgToParent (key,val) {
            this.$emit(key, val);
        }

    },
    data () {
        return {
            imgObj: {
                size: 500,
            },
            // file: "",
            imgSrc: "",
            bg: "",
        }
    }
 }
</script>

<style scoped>
    .upload-pic {
        width: 296px;
        height: 196px;
        overflow: hidden;
        position: relative;
        border: 1px solid #eee;
        border-radius: 8px;
    }
    .upload-input {
        width: 100%;
        height: 100%;
        opacity: 0;
        position: absolute;
        top: 0;
        right: 0;
        z-index: 5;
        background: rgba(0,0,0,0.10);
        border-radius: 8px;
        background: rgba(0,0,0,0.10) url() 0 0 no-repeat;
    }
    img {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        right: 0;
        z-index: 2;
    }
</style>
